package com.unione.heathrobot

import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.GONE
import android.view.View.OnClickListener
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.gson.Gson
import com.unione.healthrobot.R
import com.unione.healthrobot.databinding.ActivityMainBinding
import com.unione.heathrobot.bean.CommonDataRsp
import com.unione.heathrobot.constant.AmpParams
import com.unione.heathrobot.utils.HttpCallback
import com.unione.heathrobot.utils.HttpUtil
import com.unione.unione_network.WebSocketManager
import com.unione.unione_voice.callback.OnAIUIListener
import com.unione.unione_voice.constant.VoiceCommonConstant.ACTION_USB_PERMISSION
import com.unione.unione_voice.utils.SoundPoolUtil
import com.wch.multiport.MultiPortManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Request
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


class MainActivity : BaseCountDownActivity(), OnClickListener, OnAIUIListener {

    private val TAG: String = MainActivity::class.java.simpleName
    private lateinit var binding: ActivityMainBinding
    val mainViewModel: MainViewModel by viewModels()
    private val executorService = Executors.newScheduledThreadPool(3)
    lateinit var multiPortManager: MultiPortManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val rootView = binding.root
        setContentView(rootView)
        initListener()
        SoundPoolUtil.create()
        //  mainViewModel.initI2C()

        mainViewModel.initWebSocketManager()
    }


    override fun onPermissionGranted() {
        super.onPermissionGranted()
        initMultiPortManager()
        setAmpData()
        mainViewModel.init()
        mainViewModel.initAIUISdk()
        mainViewModel.initSparkSdk()
        mainViewModel.onAIUIListener = this
    }

    private fun initMultiPortManager() {
        multiPortManager = MultiPortManager(
            getSystemService(USB_SERVICE) as UsbManager,
            this,
            ACTION_USB_PERMISSION
        )
    }

    private fun initListener() {
        binding.btnId.setOnClickListener(this)
        binding.btnTen.setOnClickListener(this)
        binding.btnTwenty.setOnClickListener(this)
        binding.btnThirty.setOnClickListener(this)
        binding.tvSetting.setOnClickListener(this)
    }

    override fun onResume() {
        super.onResume()
        startGetDataTask()
    }


    /**
     *  设置功放参数
     */
    private fun setAmpData() {
        if (2 == multiPortManager.ResumeUsbList()) {
            multiPortManager.CloseDevice()
        } else {
            multiPortManager.CH341SystemInit()
        }
        if (!multiPortManager.CH341SetStream(0x81)) {
            //   ToastUtils.showLong("IIC mode set error")
        } else {
            for (entry in AmpParams.Reg) {
                val charArray = CharArray(3)
                charArray[0] = (AmpParams.PA_Addr shl 1).toChar()
                charArray[1] = entry.key.toChar()
                charArray[2] = entry.value.toChar()
                val isSuccess = multiPortManager.CH341StreamI2C(
                    3,
                    charArray,
                    0,
                    null
                )
                Log.i("native-i2c-log", "写数据" + isSuccess + " " + entry.key.toString())
            }
        }
    }

    private fun getAmpParams(): CharArray {
        val size = 2 + AmpParams.Reg.size
        val charArray = CharArray(size)
        charArray[0] = (AmpParams.PA_Addr shl 1).toChar()
        charArray[1] = 0x00.toChar()
        for (entry in AmpParams.Reg) {
            charArray[2 + entry.key] = entry.value.toChar()
        }
        return charArray
    }

    override fun onDestroy() {
        super.onDestroy()
        mainViewModel.onDestroy()
        executorService.shutdownNow()
        SoundPoolUtil.release()
        if (multiPortManager.isConnected) {
            multiPortManager.CloseDevice()
        }
    }

    private fun startGetDataTask() {
        val request1 = Request.Builder()
            .url("https://sswd.entsz.com/kk-server/hcr/bodytemperaturedata/getNewEst?robotNo=No.3")
            .build()
        val request2 = Request.Builder()
            .url("https://sswd.entsz.com/kk-server/hcr/bloodoxygen/getNewEst?robotNo=No.3")
            .build()
        val request3 = Request.Builder()
            .url("https://sswd.entsz.com/kk-server/hcr/hrtdata/getNewEst?robotNo=No.3")
            .build()
        executorService.scheduleWithFixedDelay(Runnable { // 体温
            HttpUtil.getInstance().getIntern(request1, object : HttpCallback {
                override fun onSuccess(response: String?) {
                    try {
                        val rsp: CommonDataRsp =
                            Gson().fromJson(response, CommonDataRsp::class.java)
                        binding.tvTemp.text = String.format("%.1f", rsp.data.value)
                    } catch (e: Exception) {
                    }
                }

                override fun onFailure(msg: String?) {}
            })
            // 血氧
            HttpUtil.getInstance().getIntern(request2, object : HttpCallback {
                override fun onSuccess(response: String?) {
                    try {
                        val rsp1: CommonDataRsp =
                            Gson().fromJson(response, CommonDataRsp::class.java)
                        binding.tvBloodOxygen.text = String.format("%.1f", rsp1.data.value)
                    } catch (e: Exception) {
                    }
                }

                override fun onFailure(msg: String?) {}
            })
//            // 心率
//            HttpUtil.getInstance().getIntern(request3, object : HttpCallback() {
//                override  fun onSuccess(response: String?) {
//                    try {
//                        val rsp1: CommonDataRsp =
//                            Gson().fromJson(response, CommonDataRsp::class.java)
//                        binding.tvXinlv.setText(
//                            java.lang.String.format(
//                                "心率：%.0f次/分",
//                                rsp1.getData().getValue()
//                            )
//                        )
//                    } catch (e: Exception) {
//                    }
//                }
//
//                override  fun onFailure(msg: String?) {}
//            })
        }, 0, 2000, TimeUnit.MILLISECONDS)

    }

    override fun onClick(v: View?) {
        if (v == null) return
        when (v.id) {
            R.id.btn_id -> ToastUtils.showShort("该功能正在完善中，请等待...")
            R.id.btn_ten -> {
                binding.btnTen.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_ten_minutes_pressed)
                binding.btnTwenty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_twenty_minutes)
                binding.btnThirty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_thirty_minutes)
                mainViewModel.startPatrolTask(10)
//                HttpUtil.getInstance().put(
//                    "http://192.168.9.70:8080/mapEdit/api/rosService/enableTiming?time=10&power=30",
//                    "string",
//                    object : HttpCallback {
//                        override fun onSuccess(response: String) {
//                            Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show()
//                        }
//
//                        override fun onFailure(msg: String) {}
//                    })
            }

            R.id.btn_twenty -> {
                binding.btnTen.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_ten_minutes)
                binding.btnTwenty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_twenty_minutes_pressed)
                binding.btnThirty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_thirty_minutes)
                mainViewModel.startPatrolTask(20)
//                HttpUtil.getInstance().put(
//                    "http://192.168.9.70:8080/mapEdit/api/rosService/enableTiming?time=20&power=30",
//                    "string",
//                    object : HttpCallback {
//                        override fun onSuccess(response: String) {
//                            Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show()
//                        }
//
//                        override fun onFailure(msg: String) {}
//                    })
            }

            R.id.btn_thirty -> {
                binding.btnTen.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_ten_minutes)
                binding.btnTwenty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_twenty_minutes)
                binding.btnThirty.background =
                    ContextCompat.getDrawable(mContext, R.drawable.ic_thirty_minutes_pressed)
                mainViewModel.startPatrolTask(30)
//                HttpUtil.getInstance().put(
//                    "http://192.168.9.70:8080/mapEdit/api/rosService/enableTiming?time=30&power=30",
//                    "string",
//                    object : HttpCallback {
//                        override fun onSuccess(response: String) {
//                            Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show()
//                        }
//
//                        override fun onFailure(msg: String) {}
//                    })
            }

            R.id.tvSetting -> {
                val settingDialog = SettingDialog(this)
                settingDialog.show()
            }
        }
    }


    private fun showImage() {
        lifecycleScope.launch(Dispatchers.Main) {
            val imgUrl = "file:///android_asset/smile.gif"
            binding.ivSmileTalk.visibility = View.VISIBLE
            Glide.with(mContext)
                .asGif()
                .load(imgUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(binding.ivSmileTalk)

        }
    }

    private fun hideImage() {
        lifecycleScope.launch(Dispatchers.Main) {
            Glide.with(mContext).clear(binding.ivSmileTalk)
            binding.ivSmileTalk.visibility = GONE
        }
    }

    override fun onWakeUp() {
        showImage()
    }

    override fun onSleep() {
        hideImage()
    }


}